<template>
	<view>
		<view class="wechat-login-btn" v-if="!user.userId">
			<button open-type="getPhoneNumber" @getphonenumber="login">登录</button>
			<view class="btn-text">登录后，随时收藏，关注</view>
		</view>
		

		<view v-else>
			<!-- 头像信息 -->
			<view class="header">
				<view class="header-head-left">
					<image :src="user.avatarUrl" mode="aspectFit" />
					<text class="user-name">{{ user.userName }}</text>
				</view>
				<view class="header-head-right">
					<image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-22/right.png"
						style="height: 20px; width: 50px" mode="aspectFit" @click="changeToUser(user.userId)" />
				</view>
			</view>

			<!-- 用户数据 -->
			<view class="data">
				<view class="data-children">
					<view class="children-data">{{ user.collect }}</view>
					<view class="children-char">关注</view>
				</view>

				<view class="data-children">
					<view class="children-data">{{ user.fans }}</view>
					<view class="children-char">粉丝</view>
				</view>

				<view class="data-children">
					<view class="children-data">{{ user.visit }}</view>
					<view class="children-char">访问</view>
				</view>

				<view class="data-children">
					<view class="children-data">--</view>
					<view class="children-char">排名</view>
				</view>
			</view>
		</view>

		<view class="icon">
			<view class="icon-children">
				<image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-22/history.png"
					style="height: 25px; width: 50%" mode="aspectFit" />
				<view class="children-char">浏览历史</view>
			</view>

			<view class="icon-children">
				<image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-22/folder-focus.png"
					style="height: 25px; width: 38%" mode="aspectFit" />
				<view class="children-char">收藏夹</view>
			</view>

			<view class="icon-children">
				<image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-22/folder-settings.png"
					style="height: 25px; width: 50%" mode="aspectFit" />
				<view class="children-char">内容管理</view>
			</view>

			<view class="icon-children">
				<image src="https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/2025-06-22/data-screen.png"
					style="height: 25px; width: 90%" mode="aspectFit" />
				<view class="children-char">内容数据</view>
			</view>
		</view>

		<!-- 退出按钮 -->
		<view class="logout-section" v-if="user.userId">
			<view class="logout-btn" @click="logout">
				<text>退出登录</text>
			</view>
		</view>
	</view>
</template>

<script>
	// pages/mine/mine.js
	import {wechatLogin, getUserInfo} from "@/api/user";

	export default {
		data() {
			return {
				user: {
					userId: '',
					userName: '',
					avatarUrl: 'https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/user-header/user_header.png',
					collect: '',
					fans: '',
					visit: ''
				},
				wxLoginForm: {
					loginCode: '',
					phoneCode: ''
				}
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			// 页面加载时检查是否已登录
			this.checkLoginStatus();
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			// 每次页面显示时都检查登录状态
			this.checkLoginStatus();
		},
		methods: {
			/**
			 * 跳转到用户页面
			 */
			changeToUser(userId) {
				uni.navigateTo({
					url: `/pages/user/user?userId=` + userId
				});
			},

			/**
			 * 检查登录状态
			 */
			checkLoginStatus() {
				// 先检查本地存储中是否有用户信息
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo) {
					try {
						this.user = JSON.parse(userInfo);
						return;
					} catch (e) {
						console.error('解析用户信息失败:', e);
					}
				}

				// 如果本地没有用户信息，检查是否有token
				const token = uni.getStorageSync("token");
				if (token) {
					// 如果有token，尝试获取用户信息
					this.getUserInfoByToken();
				}
			},

			/**
			 * 根据token获取用户信息
			 */
			async getUserInfoByToken() {
				try {
					const data = await getUserInfo();
					if (data.code === 0) {
						// 保存用户信息
						this.user = {
							userId: data.data.userId,
							userName: data.data.nickname,
							avatarUrl: data.data.avatarUrl,
							collect: data.data.followedCount,
							fans: data.data.followerCount,
							visit: data.data.visitorCount
						};
						// 将用户信息保存到本地存储
						uni.setStorageSync('userInfo', JSON.stringify(this.user));
					}
				} catch (error) {
					console.error('获取用户信息失败:', error);
					// 请求失败，也清除token
					this.handleTokenInvalid();
				}
			},

			/**
			 * 处理token无效的情况
			 */
			handleTokenInvalid() {
				// 清除token和用户信息
				uni.removeStorageSync('token');
				uni.removeStorageSync('userInfo');
				// 重置用户信息
				this.user = {
					userId: '',
					userName: '',
					avatarUrl: 'https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/user-header/user_header.png',
					collect: '',
					fans: '',
					visit: ''
				};
			},

			/**
			 * 用户登录
			 */
			async login(event) {
				const phoneCode = event.detail.code;
				
				try {
					// 1. 获取微信登录code
					const loginRes = await new Promise((resolve, reject) => {
						uni.login({
							success: resolve,
							fail: reject
						});
					});
					
					if (!loginRes.code) {
						throw new Error('获取登录凭证失败：' + loginRes.errMsg);
					}
					
					this.wxLoginForm.loginCode = loginRes.code;
					this.wxLoginForm.phoneCode = phoneCode;

					// 2. 调用微信授权登录接口，获取token
					const data = await wechatLogin(this.wxLoginForm);
					
					if (data.code === 0) {
						// 3. 保存token
						uni.setStorageSync("token", data.token);

						// 4. 根据token获取用户信息
						await this.getUserInfoByToken();
						
						// 显示登录成功提示
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
					} else {
						throw new Error(data?.message || '登录失败');
						
						uni.showToast({
							title: data.message || '登录失败，请稍后重试',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '登录失败，请稍后重试',
						icon: 'none'
					});
				} finally {
				// 隐藏加载提示
				uni.hideLoading();
			}
		},

		/**
		 * 用户退出登录
		 */
		logout() {
			uni.showModal({
				title: '退出登录',
				content: '确定要退出登录吗？',
				confirmText: '退出',
				cancelText: '取消',
				confirmColor: '#e70f0f',
				success: (res) => {
					if (res.confirm) {
						// 清除token
						uni.removeStorageSync('token');
						// 清除本地存储的用户信息
						uni.removeStorageSync('userInfo');
						// 重置用户信息
						this.user = {
							userId: '',
							userName: '',
							avatarUrl: 'https://zxs-lyblog.oss-cn-hangzhou.aliyuncs.com/user-header/user_header.png',
							collect: '',
							fans: '',
							visit: ''
						};
						// 显示退出成功提示
						uni.showToast({
							title: '退出成功',
							icon: 'success'
						});
					}
				}
			});
		}
	}
	};
</script>
<style>
	@import './mine.scss';
</style>